/*
 * plpy模块
 *
 * src/pl/plpython/plpy_plpymodule.c
 */

#include "postgres.h"

#include "access/xact.h"
#include "mb/pg_wchar.h"
#include "plpy_cursorobject.h"
#include "plpy_elog.h"
#include "plpy_main.h"
#include "plpy_planobject.h"
#include "plpy_plpymodule.h"
#include "plpy_resultobject.h"
#include "plpy_spi.h"
#include "plpy_subxactobject.h"
#include "plpython.h"
#include "utils/builtins.h"
#include "utils/snapmgr.h"

HTAB	   *PLy_spi_exceptions = NULL;


static void fc_PLy_add_exceptions(PyObject *fc_plpy);
static PyObject *fc_PLy_create_exception(char *fc_name,
									  PyObject *fc_base, PyObject *fc_dict,
									  const char *fc_modname, PyObject *fc_mod);
static void fc_PLy_generate_spi_exceptions(PyObject *fc_mod, PyObject *fc_base);

/* 模块函数 */
static PyObject *fc_PLy_debug(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw);
static PyObject *fc_PLy_log(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw);
static PyObject *fc_PLy_info(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw);
static PyObject *fc_PLy_notice(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw);
static PyObject *fc_PLy_warning(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw);
static PyObject *fc_PLy_error(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw);
static PyObject *fc_PLy_fatal(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw);
static PyObject *fc_PLy_quote_literal(PyObject *fc_self, PyObject *fc_args);
static PyObject *fc_PLy_quote_nullable(PyObject *fc_self, PyObject *fc_args);
static PyObject *fc_PLy_quote_ident(PyObject *fc_self, PyObject *fc_args);


/* 所有已知异常的列表，从backend/utils/errcodes.txt生成 */
typedef struct ExceptionMap
{
	char	   *name;
	char	   *classname;
	int			sqlstate;
} ExceptionMap;

static const ExceptionMap exception_map[] = {
#include "spiexceptions.h"
	{NULL, NULL, 0}
};

static PyMethodDef PLy_methods[] = {
	/*
	 * 日志记录方法
	 */
	{"debug", (PyCFunction) (pg_funcptr_t) fc_PLy_debug, METH_VARARGS | METH_KEYWORDS, NULL},
	{"log", (PyCFunction) (pg_funcptr_t) fc_PLy_log, METH_VARARGS | METH_KEYWORDS, NULL},
	{"info", (PyCFunction) (pg_funcptr_t) fc_PLy_info, METH_VARARGS | METH_KEYWORDS, NULL},
	{"notice", (PyCFunction) (pg_funcptr_t) fc_PLy_notice, METH_VARARGS | METH_KEYWORDS, NULL},
	{"warning", (PyCFunction) (pg_funcptr_t) fc_PLy_warning, METH_VARARGS | METH_KEYWORDS, NULL},
	{"error", (PyCFunction) (pg_funcptr_t) fc_PLy_error, METH_VARARGS | METH_KEYWORDS, NULL},
	{"fatal", (PyCFunction) (pg_funcptr_t) fc_PLy_fatal, METH_VARARGS | METH_KEYWORDS, NULL},

	/*
	 * 创建存储计划
	 */
	{"prepare", PLy_spi_prepare, METH_VARARGS, NULL},

	/*
	 * 执行计划或查询
	 */
	{"execute", PLy_spi_execute, METH_VARARGS, NULL},

	/*
	 * 字符串转义
	 */
	{"quote_literal", fc_PLy_quote_literal, METH_VARARGS, NULL},
	{"quote_nullable", fc_PLy_quote_nullable, METH_VARARGS, NULL},
	{"quote_ident", fc_PLy_quote_ident, METH_VARARGS, NULL},

	/*
	 * 创建子事务上下文管理器
	 */
	{"subtransaction", PLy_subtransaction_new, METH_NOARGS, NULL},

	/*
	 * 创建游标
	 */
	{"cursor", PLy_cursor, METH_VARARGS, NULL},

	/*
	 * 事务控制
	 */
	{"commit", PLy_commit, METH_NOARGS, NULL},
	{"rollback", PLy_rollback, METH_NOARGS, NULL},

	{NULL, NULL, 0, NULL}
};

static PyMethodDef PLy_exc_methods[] = {
	{NULL, NULL, 0, NULL}
};

static PyModuleDef PLy_module = {
	PyModuleDef_HEAD_INIT,
	.m_name = "plpy",
	.m_size = -1,
	.m_methods = PLy_methods,
};

static PyModuleDef PLy_exc_module = {
	PyModuleDef_HEAD_INIT,
	.m_name = "spiexceptions",
	.m_size = -1,
	.m_methods = PLy_exc_methods,
};

/*
 * 必须具有外部链接，因为PyMODINIT_FUNC在
 * Windows类平台上执行dllexport。
 */
PyMODINIT_FUNC
PyInit_plpy(void)
{
	PyObject   *fc_m;

	fc_m = PyModule_Create(&PLy_module);
	if (fc_m == NULL)
		return NULL;

	fc_PLy_add_exceptions(fc_m);

	return fc_m;
}

void PLy_init_plpy(void)
{
	PyObject   *fc_main_mod,
			   *fc_main_dict,
			   *fc_plpy_mod;

	/*
	 * 初始化plpy模块
	 */
	PLy_plan_init_type();
	PLy_result_init_type();
	PLy_subtransaction_init_type();
	PLy_cursor_init_type();

	PyModule_Create(&PLy_module);

	/* PyDict_SetItemString(plpy, "PlanType", (PyObject *) &PLy_PlanType); */

	/*
	 * 初始化主模块，并添加plpy
	 */
	fc_main_mod = PyImport_AddModule("__main__");
	fc_main_dict = PyModule_GetDict(fc_main_mod);
	fc_plpy_mod = PyImport_AddModule("plpy");
	if (fc_plpy_mod == NULL)
		PLy_elog(ERROR, "could not import \"plpy\" module");
	PyDict_SetItemString(fc_main_dict, "plpy", fc_plpy_mod);
	if (PyErr_Occurred())
		PLy_elog(ERROR, "could not import \"plpy\" module");
}

static void fc_PLy_add_exceptions(PyObject *fc_plpy)
{
	PyObject   *fc_excmod;
	HASHCTL		fc_hash_ctl;

	fc_excmod = PyModule_Create(&PLy_exc_module);
	if (fc_excmod == NULL)
		PLy_elog(ERROR, "could not create the spiexceptions module");

	/*
	 * PyModule_AddObject并不为对象增加引用计数，出于某种奇怪
	 * 的原因；我们必须自己做这件事。
	 */
	Py_INCREF(fc_excmod);
	if (PyModule_AddObject(fc_plpy, "spiexceptions", fc_excmod) < 0)
		PLy_elog(ERROR, "could not add the spiexceptions module");

	PLy_exc_error = fc_PLy_create_exception("plpy.Error", NULL, NULL,
										 "Error", fc_plpy);
	PLy_exc_fatal = fc_PLy_create_exception("plpy.Fatal", NULL, NULL,
										 "Fatal", fc_plpy);
	PLy_exc_spi_error = fc_PLy_create_exception("plpy.SPIError", NULL, NULL,
											 "SPIError", fc_plpy);

	fc_hash_ctl.keysize = sizeof(int);
	fc_hash_ctl.entrysize = sizeof(PLyExceptionEntry);
	PLy_spi_exceptions = hash_create("PL/Python SPI exceptions", 256,
									 &fc_hash_ctl, HASH_ELEM | HASH_BLOBS);

	fc_PLy_generate_spi_exceptions(fc_excmod, PLy_exc_spi_error);
}

/*
 * 创建一个异常对象并将其添加到模块中
 */
static PyObject * fc_PLy_create_exception(char *fc_name, PyObject *fc_base, PyObject *fc_dict,
					 const char *fc_modname, PyObject *fc_mod)
{
	PyObject   *fc_exc;

	fc_exc = PyErr_NewException(fc_name, fc_base, fc_dict);
	if (fc_exc == NULL)
		PLy_elog(ERROR, NULL);

	/*
	 * PyModule_AddObject并不为对象增加引用计数，出于某种奇怪
	 * 的原因；我们必须自己做这件事。
	 */
	Py_INCREF(fc_exc);
	PyModule_AddObject(fc_mod, fc_modname, fc_exc);

	/*
	 * 调用者还会在某个永久变量中存储指向异常对象的指针，
	 * 因此需要增加另一个引用以对此进行补偿。 这
	 * 可能过于谨慎，但我们还是要确保。
	 */
	Py_INCREF(fc_exc);
	return fc_exc;
}

/*
 * 将所有自动生成的异常作为SPIError的子类添加
 */
static void fc_PLy_generate_spi_exceptions(PyObject *fc_mod, PyObject *fc_base)
{
	int			fc_i;

	for (fc_i = 0; exception_map[fc_i].name != NULL; fc_i++)
	{
		bool		fc_found;
		PyObject   *fc_exc;
		PLyExceptionEntry *fc_entry;
		PyObject   *fc_sqlstate;
		PyObject   *fc_dict = PyDict_New();

		if (fc_dict == NULL)
			PLy_elog(ERROR, NULL);

		fc_sqlstate = PLyUnicode_FromString(unpack_sql_state(exception_map[fc_i].sqlstate));
		if (fc_sqlstate == NULL)
			PLy_elog(ERROR, "could not generate SPI exceptions");

		PyDict_SetItemString(fc_dict, "sqlstate", fc_sqlstate);
		Py_DECREF(fc_sqlstate);

		fc_exc = fc_PLy_create_exception(exception_map[fc_i].name, fc_base, fc_dict,
								   exception_map[fc_i].classname, fc_mod);

		fc_entry = hash_search(PLy_spi_exceptions, &exception_map[fc_i].sqlstate,
							HASH_ENTER, &fc_found);
		Assert(!fc_found);
		fc_entry->exc = fc_exc;
	}
}


/*
 * python接口到elog函数
 * 不要将这些与PLy_elog混淆
 */
static PyObject *fc_PLy_output(volatile int fc_level, PyObject *fc_self,
							PyObject *fc_args, PyObject *fc_kw);

static PyObject * fc_PLy_debug(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw)
{
	return fc_PLy_output(DEBUG2, fc_self, fc_args, fc_kw);
}

static PyObject * fc_PLy_log(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw)
{
	return fc_PLy_output(LOG, fc_self, fc_args, fc_kw);
}

static PyObject * fc_PLy_info(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw)
{
	return fc_PLy_output(INFO, fc_self, fc_args, fc_kw);
}

static PyObject * fc_PLy_notice(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw)
{
	return fc_PLy_output(NOTICE, fc_self, fc_args, fc_kw);
}

static PyObject * fc_PLy_warning(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw)
{
	return fc_PLy_output(WARNING, fc_self, fc_args, fc_kw);
}

static PyObject * fc_PLy_error(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw)
{
	return fc_PLy_output(ERROR, fc_self, fc_args, fc_kw);
}

static PyObject * fc_PLy_fatal(PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw)
{
	return fc_PLy_output(FATAL, fc_self, fc_args, fc_kw);
}

static PyObject * fc_PLy_quote_literal(PyObject *fc_self, PyObject *fc_args)
{
	const char *fc_str;
	char	   *fc_quoted;
	PyObject   *fc_ret;

	if (!PyArg_ParseTuple(fc_args, "s:quote_literal", &fc_str))
		return NULL;

	fc_quoted = quote_literal_cstr(fc_str);
	fc_ret = PLyUnicode_FromString(fc_quoted);
	pfree(fc_quoted);

	return fc_ret;
}

static PyObject * fc_PLy_quote_nullable(PyObject *fc_self, PyObject *fc_args)
{
	const char *fc_str;
	char	   *fc_quoted;
	PyObject   *fc_ret;

	if (!PyArg_ParseTuple(fc_args, "z:quote_nullable", &fc_str))
		return NULL;

	if (fc_str == NULL)
		return PLyUnicode_FromString("NULL");

	fc_quoted = quote_literal_cstr(fc_str);
	fc_ret = PLyUnicode_FromString(fc_quoted);
	pfree(fc_quoted);

	return fc_ret;
}

static PyObject * fc_PLy_quote_ident(PyObject *fc_self, PyObject *fc_args)
{
	const char *fc_str;
	const char *fc_quoted;
	PyObject   *fc_ret;

	if (!PyArg_ParseTuple(fc_args, "s:quote_ident", &fc_str))
		return NULL;

	fc_quoted = quote_identifier(fc_str);
	fc_ret = PLyUnicode_FromString(fc_quoted);

	return fc_ret;
}

/* 强制将对象转换为字符串 */
static char * fc_object_to_string(PyObject *fc_obj)
{
	if (fc_obj)
	{
		PyObject   *fc_so = PyObject_Str(fc_obj);

		if (fc_so != NULL)
		{
			char	   *fc_str;

			fc_str = pstrdup(PLyUnicode_AsString(fc_so));
			Py_DECREF(fc_so);

			return fc_str;
		}
	}

	return NULL;
}

static PyObject * fc_PLy_output(volatile int fc_level, PyObject *fc_self, PyObject *fc_args, PyObject *fc_kw)
{
	int			fc_sqlstate = 0;
	char	   *volatile fc_sqlstatestr = NULL;
	char	   *volatile fc_message = NULL;
	char	   *volatile fc_detail = NULL;
	char	   *volatile fc_hint = NULL;
	char	   *volatile fc_column_name = NULL;
	char	   *volatile fc_constraint_name = NULL;
	char	   *volatile fc_datatype_name = NULL;
	char	   *volatile fc_table_name = NULL;
	char	   *volatile fc_schema_name = NULL;
	volatile MemoryContext fc_oldcontext;
	PyObject   *fc_key,
			   *fc_value;
	PyObject   *volatile fc_so;
	Py_ssize_t	fc_pos = 0;

	if (PyTuple_Size(fc_args) == 1)
	{
		/*
		 * 将单个参数特殊处理以避免不必要的('tuple',)
		 * 装饰。
		 */
		PyObject   *fc_o;

		if (!PyArg_UnpackTuple(fc_args, "plpy.elog", 1, 1, &fc_o))
			PLy_elog(ERROR, "could not unpack arguments in plpy.elog");
		fc_so = PyObject_Str(fc_o);
	}
	else
		fc_so = PyObject_Str(fc_args);

	if (fc_so == NULL || ((fc_message = PLyUnicode_AsString(fc_so)) == NULL))
	{
		fc_level = ERROR;
		fc_message = dgettext(TEXTDOMAIN, "could not parse error message in plpy.elog");
	}
	fc_message = pstrdup(fc_message);

	Py_XDECREF(fc_so);

	if (fc_kw != NULL)
	{
		while (PyDict_Next(fc_kw, &fc_pos, &fc_key, &fc_value))
		{
			char	   *fc_keyword = PLyUnicode_AsString(fc_key);

			if (strcmp(fc_keyword, "message") == 0)
			{
				/* 消息不应被覆盖 */
				if (PyTuple_Size(fc_args) != 0)
				{
					PLy_exception_set(PyExc_TypeError, "argument 'message' given by name and position");
					return NULL;
				}

				if (fc_message)
					pfree(fc_message);
				fc_message = fc_object_to_string(fc_value);
			}
			else if (strcmp(fc_keyword, "detail") == 0)
				fc_detail = fc_object_to_string(fc_value);
			else if (strcmp(fc_keyword, "hint") == 0)
				fc_hint = fc_object_to_string(fc_value);
			else if (strcmp(fc_keyword, "sqlstate") == 0)
				fc_sqlstatestr = fc_object_to_string(fc_value);
			else if (strcmp(fc_keyword, "schema_name") == 0)
				fc_schema_name = fc_object_to_string(fc_value);
			else if (strcmp(fc_keyword, "table_name") == 0)
				fc_table_name = fc_object_to_string(fc_value);
			else if (strcmp(fc_keyword, "column_name") == 0)
				fc_column_name = fc_object_to_string(fc_value);
			else if (strcmp(fc_keyword, "datatype_name") == 0)
				fc_datatype_name = fc_object_to_string(fc_value);
			else if (strcmp(fc_keyword, "constraint_name") == 0)
				fc_constraint_name = fc_object_to_string(fc_value);
			else
			{
				PLy_exception_set(PyExc_TypeError,
								  "'%s' is an invalid keyword argument for this function",
								  fc_keyword);
				return NULL;
			}
		}
	}

	if (fc_sqlstatestr != NULL)
	{
		if (strlen(fc_sqlstatestr) != 5)
		{
			PLy_exception_set(PyExc_ValueError, "invalid SQLSTATE code");
			return NULL;
		}

		if (strspn(fc_sqlstatestr, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") != 5)
		{
			PLy_exception_set(PyExc_ValueError, "invalid SQLSTATE code");
			return NULL;
		}

		fc_sqlstate = MAKE_SQLSTATE(fc_sqlstatestr[0],
								 fc_sqlstatestr[1],
								 fc_sqlstatestr[2],
								 fc_sqlstatestr[3],
								 fc_sqlstatestr[4]);
	}

	fc_oldcontext = CurrentMemoryContext;
	PG_TRY();
	{
		if (fc_message != NULL)
			pg_verifymbstr(fc_message, strlen(fc_message), false);
		if (fc_detail != NULL)
			pg_verifymbstr(fc_detail, strlen(fc_detail), false);
		if (fc_hint != NULL)
			pg_verifymbstr(fc_hint, strlen(fc_hint), false);
		if (fc_schema_name != NULL)
			pg_verifymbstr(fc_schema_name, strlen(fc_schema_name), false);
		if (fc_table_name != NULL)
			pg_verifymbstr(fc_table_name, strlen(fc_table_name), false);
		if (fc_column_name != NULL)
			pg_verifymbstr(fc_column_name, strlen(fc_column_name), false);
		if (fc_datatype_name != NULL)
			pg_verifymbstr(fc_datatype_name, strlen(fc_datatype_name), false);
		if (fc_constraint_name != NULL)
			pg_verifymbstr(fc_constraint_name, strlen(fc_constraint_name), false);

		ereport(fc_level,
				((fc_sqlstate != 0) ? errcode(fc_sqlstate) : 0,
				 (fc_message != NULL) ? errmsg_internal("%s", fc_message) : 0,
				 (fc_detail != NULL) ? errdetail_internal("%s", fc_detail) : 0,
				 (fc_hint != NULL) ? errhint("%s", fc_hint) : 0,
				 (fc_column_name != NULL) ?
				 err_generic_string(PG_DIAG_COLUMN_NAME, fc_column_name) : 0,
				 (fc_constraint_name != NULL) ?
				 err_generic_string(PG_DIAG_CONSTRAINT_NAME, fc_constraint_name) : 0,
				 (fc_datatype_name != NULL) ?
				 err_generic_string(PG_DIAG_DATATYPE_NAME, fc_datatype_name) : 0,
				 (fc_table_name != NULL) ?
				 err_generic_string(PG_DIAG_TABLE_NAME, fc_table_name) : 0,
				 (fc_schema_name != NULL) ?
				 err_generic_string(PG_DIAG_SCHEMA_NAME, fc_schema_name) : 0));
	}
	PG_CATCH();
	{
		ErrorData  *fc_edata;

		MemoryContextSwitchTo(fc_oldcontext);
		fc_edata = CopyErrorData();
		FlushErrorState();

		PLy_exception_set_with_details(PLy_exc_error, fc_edata);
		FreeErrorData(fc_edata);

		return NULL;
	}
	PG_END_TRY();

	/*
	 * 返回一个合法对象，以便解释器可以继续其正常工作
	 */
	Py_RETURN_NONE;
}
